/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 * Description: 获取动态库中hdds接口函数的适配接口
 * Author: qingjicheng
 * Create: 2022-11-18
 */
#include "dlhdds_function.h"
#include "log.h"
#include "hccl_dl.h"

namespace hccl {
DlHddsFunction &DlHddsFunction::GetInstance()
{
    static DlHddsFunction hcclDlHddsFunction;
    return hcclDlHddsFunction;
}

DlHddsFunction::DlHddsFunction() : handle_(nullptr)
{
}

DlHddsFunction::~DlHddsFunction()
{
    if (handle_ != nullptr) {
        (void)HcclDlclose(handle_);
        handle_ = nullptr;
    }
}

HcclResult DlHddsFunction::DlHddsFunctionApiInit()
{
    dlQueryPartitionMapPsId = (s32(*)(u64, u32 *))HcclDlsym(handle_, "QueryPartitionMapPsId");
    CHK_SMART_PTR_NULL(dlQueryPartitionMapPsId);

    dlInitPartitionMap = (s32(*)(u32, u32, const u32*))HcclDlsym(handle_, "InitPartitionMap");
    CHK_SMART_PTR_NULL(dlInitPartitionMap);

    dlGetBatchPsIds = (s32(*)(u64 *, u32 **, u32))HcclDlsym(handle_, "GetBatchPsIds");
    CHK_SMART_PTR_NULL(dlGetBatchPsIds);

    return HCCL_SUCCESS;
}

HcclResult DlHddsFunction::DlHddsFunctionInit()
{
    std::lock_guard<std::mutex> lock(handleMutex_);
    if (handle_ == nullptr) {
        handle_ = HcclDlopen("libhdds_base.so", RTLD_NOW);
        const char* errMsg = dlerror();
        CHK_PRT_RET(handle_ == nullptr, HCCL_ERROR("dlopen [%s] failed, %s", "libhdds_base.so",\
            (errMsg == nullptr) ? "please check the file exist or permission denied." : errMsg),\
            HCCL_E_OPEN_FILE_FAILURE);
    }
    CHK_RET(DlHddsFunctionApiInit());
    return HCCL_SUCCESS;
}
}